package io.github.cubelitblade.librarymanagementbackend.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.cubelitblade.librarymanagementbackend.entity.Book;
import io.github.cubelitblade.librarymanagementbackend.entity.Category;
import io.github.cubelitblade.librarymanagementbackend.mapper.CategoryMapper;
import io.github.cubelitblade.librarymanagementbackend.vo.CategoryWithBooksVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {

    //调用应该BookService类的参数便于通过Category的Id获取对于的Book信息
    private final BookService bookService;
    private final CategoryMapper categoryMapper;
    @Autowired
    public CategoryService(BookService bookService, CategoryMapper categoryMapper) {
        this.bookService = bookService;
        this.categoryMapper = categoryMapper;
    }


    //查询现有书籍的分类情况，返回所有的分类编号以及该编号代表的分类名称
    public List<Category> getAllCategories() {
        // 创建一个LambdaQueryWrapper，添加排序条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getId); // 按id升序排列
        return categoryMapper.selectList(queryWrapper);
    }

    // 获取所有分类下的图书
    public CategoryWithBooksVO getAllBooks(int page, int size){
        Page<Book> bookPage = bookService.getAllBooks(page, size);
        // 3. 封装返回对象
        return new CategoryWithBooksVO(
                null,
                bookPage.getRecords(),
                bookPage.getTotal(),
                bookPage.getPages(),
                bookPage.getCurrent(),
                bookPage.getSize()
        );
    }

    // 查询分类以及该分类下的所有书籍（分页）
    public CategoryWithBooksVO getCategoryWithBooks(Integer categoryId, int page, int size) {
        // 1. 查分类信息
        Category category = this.getById(categoryId);
        if (category == null) {
            return null;
        }

        // 2. 查该分类下分页后的书籍
        Page<Book> bookPage = bookService.getBooksByCategoryId(categoryId, page, size);

        // 3. 封装返回对象
        return new CategoryWithBooksVO(
                category,
                bookPage.getRecords(),
                bookPage.getTotal(),
                bookPage.getPages(),
                bookPage.getCurrent(),
                bookPage.getSize()
        );
    }

    // 根据分类id获取分类名称
    public String getCategoryNameById(Integer categoryId) {
        return categoryMapper.selectById(categoryId).getName();
    }

}
